package com.tongcao.cn.processor;

import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Author:tongcao
 * @Date:2018/12/28 16:47
 * Description:
 */
@Component
public class BeanHelper implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 通过名称获取bean
     *
     * @param name
     * @param t
     * @param <T>
     * @return
     */
    public <T> T getBean(String name, Class<T> t) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 获取这个类型的所有bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> getBeanList(Class<T> clazz) {
        Map<String, T> beanMap = applicationContext.getBeansOfType(clazz);
        List<T> beanList = Lists.newArrayList(beanMap.values());
        return beanList;
    }
}
